// const config = require('../config/config')
const { HttpException } = require('../cors/http-exception')
const { PositiveIntegerValidator } = require("../validators/validator")
const catchError = async (ctx, next) => {
    try {
        await next()
    } catch (error) {

        //堆栈调用的信息
        //应该简化清晰明了的信息给前端
        //HTTP Status Code 2xx 4xx 5xx
        //message
        //开发者自己定义的 1000 2000等
        //request_url 当前请求url 
        //开发环境 and 生产环境
        // 开发环境
        const isHttpException = error instanceof HttpException
        const isDev = global.config.environment === 'dev'

        if (isDev && !isHttpException) {
            
            throw error
        }

        // 生成环境
        if (isHttpException) {
            ctx.body = {
                msg: error.msg,
                error_code: error.errorCode,
                request: `${ctx.method} ${ctx.path}`
            }
            ctx.status = error.code

        } else {
            ctx.body = {
                msg: "未知错误！",
                error_code: 9999,
                request: `${ctx.method} ${ctx.path}`
            }
            ctx.status = 500
        }
    }
}

module.exports = catchError